﻿CREATE FUNCTION [QIC].[CallFactory_VDELETE](@Token QIC.TokenTable READONLY, @CallerId INT, @CalleeId INT, @ReturnPropertName VARCHAR(50), @TokenMap VARCHAR(50), @Indent INT, @CalleeDelegateName varchar(50))
RETURNS VARCHAR(MAX)
AS
BEGIN

	DECLARE @Call VARCHAR(MAX) 
	DECLARE @KeySQL VARCHAR(MAX)	
	DECLARE @CalleeView VARCHAR(MAX)
	DECLARE @Keys TABLE (CallerPropertyName varchar(50), CalleePropertyName varchar(50))

	SET @KeySQL = ''

	SELECT @CalleeView = QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name) from sys.objects WHERE object_id = @CalleeId

	INSERT INTO @Keys (CallerPropertyName,CalleePropertyName)
	SELECT CallerPropertyName,CalleePropertyName FROM QIC.KeyResolve_(@Token, @CallerId, @CalleeId, @TokenMap)

	SELECT @KeySQL += @CalleeView + '.' + QUOTENAME(CallerPropertyName) + ' = deleted.' + QUOTENAME(CalleePropertyName) + ' AND ' from QIC.KeyResolve_(@Token, @CallerId, @CalleeId, @TokenMap)

	IF LEN(@KeySQL) > 0
	BEGIN
		SET @KeySQL = LEFT(@KeySQL, DATALENGTH(@KeySQL) - DATALENGTH(' AND '))

		SET @Call = ''
		SET @Call += 
			QIC.Indent(@Indent) + 'DELETE ' + @CalleeView + QIC.LB() +
			QIC.Indent(@Indent) + 'FROM deleted'  + QIC.LB() +
			QIC.Indent(@Indent) + 'WHERE ' + @KeySQL

	END

	RETURN @Call

END
